/*
 * @Descripttion: 
 * @version: 
 * @Author: congsir
 * @Date: 2022-05-25 14:16:14
 * @LastEditors: 
 * @LastEditTime: 2022-08-05 16:21:08
 */

import { _decorator, Component, Node, Vec3, MeshRenderer,RenderableComponent, Vec4, Label, find, Camera, Material, EffectAsset, renderer } from 'cc';
const { ccclass, property } = _decorator;

 export enum MeshTextureAlignType{
    LOCAL,
    WORLOD,
}

 
@ccclass('MeshController')
export class MeshController extends Component {
    // [1]
    // dummy = '';

    // [2]
    // @property
    // serializableDummy = 0;

    @property
    textureScale =50;

    @property(Node)
    nameLabel:Node = null;

    @property(Camera)
    public mainCamera :Camera= null;



    private curMeshTextrueAlignType:MeshTextureAlignType =MeshTextureAlignType.WORLOD;

  
    start () {
        // [3]
        this.setNameLabelPos();
    }

    public update(){
        this.setNameLabelPos();
    }

    public setNameLabelPos(){
     let UIpos =  this.mainCamera.convertToUINode(this.node.worldPosition,this.nameLabel.parent)
     this.nameLabel.setPosition(UIpos.clone())
    }


   public setScale(scale:Vec3){

        this.node.setScale(scale);
        if(this.curMeshTextrueAlignType===MeshTextureAlignType.LOCAL){
            this.useLocalTilling();

        }else{
            this.useWorldTilling();
        }
   }

   //设置对齐方式
   public setMeshTextureAlignType(type:MeshTextureAlignType){
    this.curMeshTextrueAlignType = type;
      // 获取渲染器组件
      let renderableComponent = this.node.getComponent(MeshRenderer) as RenderableComponent;
      // 获取材质实例数组中索引为 0 的元素，若没有则根据当前材质创建
    
      const mat = renderableComponent.material;
    if(this.curMeshTextrueAlignType===MeshTextureAlignType.LOCAL){
        mat.recompileShaders({ IS_ALIGN_WORLD: false });
      
    }else{
        mat.recompileShaders({ IS_ALIGN_WORLD: true });
    }

   }

   //对齐本地坐标系 移动模型，纹理不会动
   public useLocalTilling(){
   // 获取渲染器组件
   let renderableComponent = this.node.getComponent(MeshRenderer) as RenderableComponent;
   // 获取材质实例
   let materialInstance = renderableComponent.getMaterialInstance(0); 
   materialInstance.setProperty("textureSize", new Vec4(this.textureScale,this.textureScale,this.textureScale,1))
   }




   //对齐世界坐标系 移动模型，纹理会动
   public useWorldTilling(){
    let renderableComponent = this.node.getComponent(MeshRenderer) as RenderableComponent;
    // 获取材质实例数组中索引为 0 的
    let materialInstance = renderableComponent.material; 
   materialInstance.setProperty("textureScale", this.textureScale)

   }
}

